/*
 * VentanaPrincipal.java
 *
 * Created on Sep 10, 2012, 6:14:17 PM
 */
package Interfaz;
import java.awt.Color;
import Procesos.ArmarArbol;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import Procesos.LeerArchivo;
import Procesos.GestorEntidad;
import Procesos.GestorEstructuraDTD;
import Procesos.Validaciones;
import negocio.DTDFileFilter;
import negocio.EntidadXML;
import negocio.XMLFileFilter;
import help.InstruccionesDeUso;

/**
 *
 * @author Emiliano
 */
public class VentanaPrincipal extends javax.swing.JFrame {

    public static ArrayList<EntidadXML> entidades = null;
    public static int tamanioConsola;
    public DefaultMutableTreeNode nodoSelecionado = null;
    public static String rutaArchivoAbierto = null;
    
    public VentanaPrincipal() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTable = new javax.swing.JTabbedPane();
        jPXml = new javax.swing.JPanel();
        btnAbrirXml = new javax.swing.JButton();
        txtAbrirXml = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtXml = new javax.swing.JTextArea();
        btnArmarArbol = new javax.swing.JButton();
        lblXmlParcear = new javax.swing.JLabel();
        chkValidarXml = new javax.swing.JCheckBox();
        chkValidarDoctype = new javax.swing.JCheckBox();
        btnValidarXml = new javax.swing.JButton();
        jPDtd = new javax.swing.JPanel();
        btnAbrirDTD = new javax.swing.JButton();
        txtAbrirDTD = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDtd = new javax.swing.JTextArea();
        btnVerificarDtd = new javax.swing.JButton();
        jPArbol = new javax.swing.JPanel();
        btnAguegarNodo = new javax.swing.JButton();
        btnActualizarCodXml = new javax.swing.JButton();
        btnAgregarElementoNodo = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTArbol = new javax.swing.JTree();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtConsola = new javax.swing.JTextArea();
        lblConsola = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMIGuardarXML = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMAyuda = new javax.swing.JMenu();
        jMIInstrucciones = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Parse XML AFA");

        jTable.setName(""); // NOI18N

        btnAbrirXml.setText("Abrir XML");
        btnAbrirXml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirXmlActionPerformed(evt);
            }
        });

        txtXml.setColumns(20);
        txtXml.setEditable(false);
        txtXml.setRows(5);
        txtXml.setEnabled(false);
        txtXml.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtXmlKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(txtXml);

        btnArmarArbol.setText("Armar Árbol");
        btnArmarArbol.setEnabled(false);
        btnArmarArbol.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnArmarArbolActionPerformed(evt);
            }
        });

        lblXmlParcear.setText("XML para Parsear:");

        chkValidarXml.setSelected(true);
        chkValidarXml.setText("Validar declaracion XML");
        chkValidarXml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkValidarXmlActionPerformed(evt);
            }
        });

        chkValidarDoctype.setText("Validar declaración DOCTYPE");

        btnValidarXml.setText("Validar XML");
        btnValidarXml.setEnabled(false);
        btnValidarXml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValidarXmlActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPXmlLayout = new javax.swing.GroupLayout(jPXml);
        jPXml.setLayout(jPXmlLayout);
        jPXmlLayout.setHorizontalGroup(
            jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPXmlLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .addGroup(jPXmlLayout.createSequentialGroup()
                        .addGroup(jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPXmlLayout.createSequentialGroup()
                                .addComponent(txtAbrirXml, javax.swing.GroupLayout.PREFERRED_SIZE, 547, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnAbrirXml))
                            .addComponent(lblXmlParcear))
                        .addGap(0, 146, Short.MAX_VALUE))
                    .addGroup(jPXmlLayout.createSequentialGroup()
                        .addComponent(chkValidarDoctype)
                        .addGap(18, 18, 18)
                        .addComponent(chkValidarXml)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 276, Short.MAX_VALUE)
                        .addComponent(btnValidarXml)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnArmarArbol)))
                .addContainerGap())
        );
        jPXmlLayout.setVerticalGroup(
            jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPXmlLayout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtAbrirXml, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAbrirXml))
                .addGap(27, 27, 27)
                .addComponent(lblXmlParcear)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPXmlLayout.createSequentialGroup()
                        .addGroup(jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkValidarDoctype)
                            .addComponent(chkValidarXml))
                        .addGap(0, 24, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPXmlLayout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(jPXmlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnValidarXml)
                            .addComponent(btnArmarArbol))
                        .addContainerGap())))
        );

        jTable.addTab("XML", jPXml);

        btnAbrirDTD.setText("Abrir DTD");
        btnAbrirDTD.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirDTDActionPerformed(evt);
            }
        });

        jLabel2.setText("Estructura DTD:");

        txtDtd.setEditable(false);
        txtDtd.setColumns(20);
        txtDtd.setRows(5);
        jScrollPane2.setViewportView(txtDtd);

        btnVerificarDtd.setText("Verificar DTD con XML");
        btnVerificarDtd.setEnabled(false);
        btnVerificarDtd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerificarDtdActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPDtdLayout = new javax.swing.GroupLayout(jPDtd);
        jPDtd.setLayout(jPDtdLayout);
        jPDtdLayout.setHorizontalGroup(
            jPDtdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPDtdLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPDtdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnVerificarDtd)
                    .addGroup(jPDtdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addGroup(jPDtdLayout.createSequentialGroup()
                            .addComponent(txtAbrirDTD, javax.swing.GroupLayout.PREFERRED_SIZE, 552, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(btnAbrirDTD))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 778, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(89, 89, 89))
        );
        jPDtdLayout.setVerticalGroup(
            jPDtdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPDtdLayout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(jPDtdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtAbrirDTD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAbrirDTD))
                .addGap(29, 29, 29)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnVerificarDtd)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jTable.addTab("DTD", jPDtd);

        btnAguegarNodo.setText("Agregar Nuevo Nodo");
        btnAguegarNodo.setEnabled(false);
        btnAguegarNodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAguegarNodoActionPerformed(evt);
            }
        });

        btnActualizarCodXml.setText("Actualizar Codigo XML");
        btnActualizarCodXml.setEnabled(false);
        btnActualizarCodXml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarCodXmlActionPerformed(evt);
            }
        });

        btnAgregarElementoNodo.setText("Agregar Elemento en Nodo");
        btnAgregarElementoNodo.setEnabled(false);
        btnAgregarElementoNodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarElementoNodoActionPerformed(evt);
            }
        });

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("ArbolXML");
        jTArbol.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTArbol.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTArbolMouseClicked(evt);
            }
        });
        jTArbol.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTArbolKeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jTArbol);

        jLabel3.setText("Estructura en forma de arbol del archivo XML:");

        javax.swing.GroupLayout jPArbolLayout = new javax.swing.GroupLayout(jPArbol);
        jPArbol.setLayout(jPArbolLayout);
        jPArbolLayout.setHorizontalGroup(
            jPArbolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPArbolLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPArbolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPArbolLayout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(516, Short.MAX_VALUE))
                    .addGroup(jPArbolLayout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 417, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(95, 95, 95)
                        .addGroup(jPArbolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnAguegarNodo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
                            .addComponent(btnActualizarCodXml, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
                            .addComponent(btnAgregarElementoNodo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE))
                        .addGap(117, 117, 117))))
        );

        jPArbolLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnActualizarCodXml, btnAgregarElementoNodo, btnAguegarNodo});

        jPArbolLayout.setVerticalGroup(
            jPArbolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPArbolLayout.createSequentialGroup()
                .addGroup(jPArbolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPArbolLayout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPArbolLayout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(btnAguegarNodo, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(btnAgregarElementoNodo, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(37, 37, 37)
                        .addComponent(btnActualizarCodXml, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 132, Short.MAX_VALUE)))
                .addGap(17, 17, 17))
        );

        jPArbolLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnActualizarCodXml, btnAgregarElementoNodo, btnAguegarNodo});

        jTable.addTab("Árbol", jPArbol);

        txtConsola.setColumns(20);
        txtConsola.setEditable(false);
        txtConsola.setRows(5);
        jScrollPane4.setViewportView(txtConsola);

        lblConsola.setText("Consola:");

        jMenu2.setText("Archivo");

        jMenuItem1.setText("Guardar");
        jMenuItem1.setEnabled(false);
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMIGuardarXML.setText("Guardar como");
        jMIGuardarXML.setEnabled(false);
        jMIGuardarXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMIGuardarXMLActionPerformed(evt);
            }
        });
        jMenu2.add(jMIGuardarXML);

        jMenuItem2.setText("Salir");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        jMAyuda.setText("Ayuda");
        jMAyuda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMAyudaActionPerformed(evt);
            }
        });

        jMIInstrucciones.setText("Instrucciones de Uso");
        jMIInstrucciones.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMIInstruccionesActionPerformed(evt);
            }
        });
        jMAyuda.add(jMIInstrucciones);

        jMenuBar1.add(jMAyuda);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblConsola)
                    .addComponent(jTable, javax.swing.GroupLayout.PREFERRED_SIZE, 805, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jTable, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblConsola)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTable.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnAbrirDTDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirDTDActionPerformed
 JFileChooser filechooser = new JFileChooser();
        filechooser.setCurrentDirectory(new File("C:\\"));
        filechooser.setFileFilter(new DTDFileFilter());

        int returnVal = filechooser.showOpenDialog(this);
        String direccion = "";
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = filechooser.getSelectedFile();
            //direccion absoluta del archivo
            direccion = file.getAbsolutePath();
            //setea en jTFied la ruta del archivo
            txtAbrirDTD.setText(direccion);

            //LeerArchivo.setDireccionArchivoDTD(direccion);
            LeerArchivo.leer(direccion, txtDtd);

            this.txtDtd.setBackground(Color.white);
            this.txtDtd.setEnabled(true);
           
        }
}//GEN-LAST:event_btnAbrirDTDActionPerformed

private void btnVerificarDtdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerificarDtdActionPerformed
  if(!txtDtd.getText().isEmpty())
  {     String dtdTextArea = txtDtd.getText();
        String mensaje = GestorEstructuraDTD.procesarComparacionDTD(dtdTextArea);

        if (mensaje == null) {
            JOptionPane.showOptionDialog(this, "Formato no valido del archivo dtd. \nCargue un archivo valido.", "Error !", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);

        } else {
            if (mensaje.equals("")) {
                mensaje = "CORRECTO. La estructura del xml se corresponde con la especificacion del archivo DTD\n";
            }
        }
  
        //limpia la consola
        imprimirMensajeConsola(null);
        //imprime el mensaje por consola
        imprimirMensajeConsola(mensaje);
  }
  else
  {
     JOptionPane.showOptionDialog(this, "Seleccione un archivo DTD", "Archivo DTD", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null); 
  }
}//GEN-LAST:event_btnVerificarDtdActionPerformed

private void btnAgregarElementoNodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarElementoNodoActionPerformed
    VentanaCargarElemento vce = new VentanaCargarElemento(this);
    vce.setVisible(true);
}//GEN-LAST:event_btnAgregarElementoNodoActionPerformed

private void btnAguegarNodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAguegarNodoActionPerformed
        VentanaAgregarNodo van = new VentanaAgregarNodo(this);
        van.setVisible(true);
}//GEN-LAST:event_btnAguegarNodoActionPerformed

private void btnActualizarCodXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarCodXmlActionPerformed
//recorrer los nodos
        TreeNode raiz = (TreeNode) getArbol().getModel().getRoot();

        String SRaiz = raiz.toString();
        String SXml = "<" + SRaiz + ">\n";
        if (raiz.getChildCount() >= 0) {
            for (Enumeration e = raiz.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();


                SXml = SXml + "<" + n.toString() + ">\n";
                for (Enumeration a = n.children(); a.hasMoreElements();) {
                    TreeNode n2 = (TreeNode) a.nextElement();
                    String aux[] = n2.toString().split("-");  //separa en el array nombreEtiqueta y Valor

                    SXml = SXml + "<" + aux[0].trim() + ">" + aux[1].trim() + "</" + aux[0].trim() + ">\n";

                }
                SXml = SXml + "</" + n.toString() + ">\n";
            }
            SXml = SXml + "</" + SRaiz + ">";
            if (!Validaciones.lineaDeclaracion.toString().equals("")) {
                SXml = Validaciones.lineaDeclaracion.getLine() + "\n" + SXml;
            }

            Validaciones.lineaDeclaracion.setLine("");
        }

        txtXml.setText("");
        txtXml.setText(SXml);
        txtConsola.setText("");
        JOptionPane.showOptionDialog(this, "Se modificó el código XML", "Código XML", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        jTable.setSelectedIndex(0);
}//GEN-LAST:event_btnActualizarCodXmlActionPerformed

private void jMIGuardarXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIGuardarXMLActionPerformed
if (txtXml.getText().compareTo("") == 0) {
            JOptionPane.showOptionDialog(this, "Debe abrir y analizar un archivo xml previamente.", "Error !", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
        } else {
            JFileChooser filechooser = new JFileChooser();
            filechooser.setCurrentDirectory(new File("C:\\"));
            filechooser.setFileFilter(new XMLFileFilter());

            int returnVal = filechooser.showSaveDialog(this);
            String direccion = "";
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = filechooser.getSelectedFile();

                //direccion absoluta del archivo
                direccion = file.getAbsolutePath() + ".xml";
                try {
                    String lineaArchivo;
                    String fuenteArchivo = txtXml.getText();
                    BufferedReader fuenteSalida;

                    fuenteSalida = new BufferedReader(new StringReader(fuenteArchivo));
                    PrintWriter archivoSalida = null;
                  
                    archivoSalida = new PrintWriter(new BufferedWriter(new FileWriter(direccion)));
                    while ((lineaArchivo = fuenteSalida.readLine()) != null) {
                        archivoSalida.println(lineaArchivo);
                    }
                    JOptionPane.showOptionDialog(this, "El archivo se guardo correctamente", "Aviso", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                    archivoSalida.close();
                } catch (IOException e) {
                    JOptionPane.showOptionDialog(this, "Error al intentar guardar el archivo. Compruebe que el disco no este lleno ni protegido contra escritura.", "Atencion!", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                    System.out.println("Excepcion Entrada/Salida");
                }
            }
        }
}//GEN-LAST:event_jMIGuardarXMLActionPerformed

private void jMAyudaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMAyudaActionPerformed
   
}//GEN-LAST:event_jMAyudaActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed

    if (JOptionPane.showOptionDialog(this, "Esta seguro que quiere salir de la aplicación?", "Salir", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null)== JOptionPane.YES_OPTION){
            System.exit(0);
    }       
}//GEN-LAST:event_jMenuItem2ActionPerformed

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
 if (!txtXml.getText().trim().equals("")) {
            String direccion = "";
            File file = new File(rutaArchivoAbierto);

            //direccion absoluta del archivo
            direccion = file.getAbsolutePath();
            try {
                String lineaArchivo;
                String fuenteArchivo = txtXml.getText();
                BufferedReader fuenteSalida;

                fuenteSalida = new BufferedReader(new StringReader(fuenteArchivo));
                PrintWriter archivoSalida = null;

                archivoSalida = new PrintWriter(new BufferedWriter(new FileWriter(direccion)));
                while ((lineaArchivo = fuenteSalida.readLine()) != null) {
                    archivoSalida.println(lineaArchivo);
                }
                
                JOptionPane.showOptionDialog(this, "El archivo se guardo correctamente", "Aviso", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                archivoSalida.close();

            } catch (IOException e) {
                JOptionPane.showOptionDialog(this, "Error al intentar guardar el archivo. Compruebe que el disco no este lleno ni protegido contra escritura.", "Atencion!", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                System.out.println("Excepcion Entrada/Salida");
                

            }
        } else {

            JOptionPane.showOptionDialog(this, "Debe abrir un archivo previamente.", "Atencion!", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
        }
}//GEN-LAST:event_jMenuItem1ActionPerformed

private void jTArbolKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTArbolKeyReleased
if (evt.getKeyCode() == 127) 
    {
        if(!nodoSelecionado.isRoot())
        {     int res = JOptionPane.showConfirmDialog(this, "¿Estás seguro de eliminar?", "Confirmar eliminación", JOptionPane.YES_NO_OPTION);

                if (nodoSelecionado != null && res == JOptionPane.YES_OPTION) {
                    DefaultTreeModel modelo = (DefaultTreeModel) getArbol().getModel();
                    modelo.removeNodeFromParent(nodoSelecionado);
                    getArbol().setModel(modelo);
                    nodoSelecionado = null;
                }
        }
        else
        {
            JOptionPane.showOptionDialog(this, "No se puede eliminar el elemento Raiz", "Atencion!", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
        }
    }
}//GEN-LAST:event_jTArbolKeyReleased

private void jTArbolMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTArbolMouseClicked
        btnAgregarElementoNodo.setEnabled(false);

        TreePath p = getArbol().getClosestPathForLocation(evt.getX(), evt.getY());

        nodoSelecionado = (DefaultMutableTreeNode) p.getLastPathComponent();
        String etiqueta = nodoSelecionado.toString();

        if (nodoSelecionado != null) {
            if (!nodoSelecionado.isRoot()) {
                String aux[] = etiqueta.split("-");
            }

            if (nodoSelecionado.isLeaf()) {
            } else {
                if (!nodoSelecionado.isRoot()) {
                    btnAgregarElementoNodo.setEnabled(true);
                }
            }
        }
}//GEN-LAST:event_jTArbolMouseClicked

private void jMIInstruccionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIInstruccionesActionPerformed
    InstruccionesDeUso ayuda = new InstruccionesDeUso();
    ayuda.setVisible(true);
}//GEN-LAST:event_jMIInstruccionesActionPerformed

    private void btnValidarXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValidarXmlActionPerformed

        String xmlTextArea = txtXml.getText();
        imprimirMensajeConsola(null);

        if (txtXml.getText().equals("")) {

            JOptionPane.showMessageDialog(this, "Debe abrir un archivo XML para realizar la validación.", "Aceptar", JOptionPane.INFORMATION_MESSAGE);
        } else {
            boolean validacionCorrecta = Validaciones.validarXML(xmlTextArea);

            if (validacionCorrecta) {
                btnArmarArbol.setEnabled(true);
                btnVerificarDtd.setEnabled(true);
                //limpia la consola

                //imprimer mensaje en consola
                imprimirMensajeConsola("VALIDACION CORRECTA DEL ARCHIVO XML");

            } else {
                btnArmarArbol.setEnabled(false);
                btnVerificarDtd.setEnabled(false);
            }
        }

    }//GEN-LAST:event_btnValidarXmlActionPerformed

    private void chkValidarXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkValidarXmlActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_chkValidarXmlActionPerformed

    private void btnArmarArbolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnArmarArbolActionPerformed

        EntidadXML raiz = null;

        //arma en memoria el arbol
        for (Iterator<EntidadXML> it = GestorEntidad.listaEntidades.iterator(); it.hasNext();) {
            EntidadXML entidad = it.next();
            if (entidad.isEsRaiz()) {
                raiz = entidad;
                break;
            }
        }
        //arma el arbol grafico
        btnActualizarCodXml.setEnabled(true);
        btnAguegarNodo.setEnabled(true);
        ArmarArbol aA = new ArmarArbol();
        aA.armarArbol(raiz, this);
        this.jMIGuardarXML.setEnabled(true);
        this.jMenuItem1.setEnabled(true);
        JOptionPane.showOptionDialog(this, "Se creó Árbol del XML", "Árbol", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        //foco en el Arbol
        jTable.setSelectedIndex(2);
    }//GEN-LAST:event_btnArmarArbolActionPerformed

    private void txtXmlKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtXmlKeyReleased
        //pone los botones armar arbool y verificar dtd en false para
        // que verifique de nuevo cuando se modifica el xml
        btnArmarArbol.setEnabled(false);
        btnVerificarDtd.setEnabled(false);
    }//GEN-LAST:event_txtXmlKeyReleased

    private void btnAbrirXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirXmlActionPerformed

        JFileChooser filechooser = new JFileChooser();
        filechooser.setCurrentDirectory(new File("C:\\"));
            filechooser.setFileFilter(new XMLFileFilter());

            int returnVal = filechooser.showOpenDialog(this); //En el entero se guardará el botón que se apreto. Debemos comprobar si es el botón de "Abrir"
            String direccion = "";
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = filechooser.getSelectedFile();
                //direccion absoluta del archivo
                direccion = file.getAbsolutePath();
                //setea en jTFied la ruta del archivo
                txtAbrirXml.setText(direccion);
                rutaArchivoAbierto = direccion;

                //LeerArchivo.setDireccionArchivo(direccion);
                LeerArchivo.leer(direccion, txtXml);

                this.btnValidarXml.setEnabled(true);
                this.txtXml.setBackground(Color.white);
                this.txtXml.setEnabled(true);
            }
    }//GEN-LAST:event_btnAbrirXmlActionPerformed

public void inicializarArbol(DefaultMutableTreeNode raiz) {
        DefaultTreeModel modelo = (DefaultTreeModel) getArbol().getModel();
        modelo.setRoot(raiz);
        getArbol().setModel(modelo);
    }

/**
     * muestra un mensaje por consola, para limpiar la consola mensaje
     * @param mensaje que se quiere mostrar en consola
     * @param color del mensaje
     */
    public static void imprimirMensajeConsola(String mensaje) {
        if (mensaje == null) {   //limpia la consola
            txtConsola.setText("");
        } else {            
            try {//escribe el mensaje por consola
                txtConsola.setText(mensaje);
            } catch (Exception ex) {
                System.out.println("Error al imprimir en consola: " + ex);
            }

            txtConsola.setForeground(Color.BLACK);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new VentanaPrincipal().setVisible(true);
            }
        });
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAbrirDTD;
    private javax.swing.JButton btnAbrirXml;
    private javax.swing.JButton btnActualizarCodXml;
    private javax.swing.JButton btnAgregarElementoNodo;
    private javax.swing.JButton btnAguegarNodo;
    private javax.swing.JButton btnArmarArbol;
    private javax.swing.JButton btnValidarXml;
    private javax.swing.JButton btnVerificarDtd;
    public static javax.swing.JCheckBox chkValidarDoctype;
    public static javax.swing.JCheckBox chkValidarXml;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMAyuda;
    private javax.swing.JMenuItem jMIGuardarXML;
    private javax.swing.JMenuItem jMIInstrucciones;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPArbol;
    private javax.swing.JPanel jPDtd;
    private javax.swing.JPanel jPXml;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTree jTArbol;
    private javax.swing.JTabbedPane jTable;
    private javax.swing.JLabel lblConsola;
    private javax.swing.JLabel lblXmlParcear;
    private javax.swing.JTextField txtAbrirDTD;
    private javax.swing.JTextField txtAbrirXml;
    public static javax.swing.JTextArea txtConsola;
    private javax.swing.JTextArea txtDtd;
    private javax.swing.JTextArea txtXml;
    // End of variables declaration//GEN-END:variables

    public javax.swing.JTree getArbol() {
        return jTArbol;
    }

    /**
     * @param arbol the arbol to set
     */
    public void setArbol(javax.swing.JTree arbol) {
        this.jTArbol = arbol;
    }

}
